<?php
namespace app\admin\controller;
use app\admin\model\Article as ArticleModel;
use app\admin\model\Jiejue as JiejueModel;
use app\common\service\CateService;
use app\admin\model\Cate as CateModel;
use think\facade\Request;
use app\admin\traits\Result;
use think\validate;
use think\Db;
use PHPExcel\PHPExcel;
use library\ArrayOperate;

class Article extends Common
{
    
    public function index(){
		$uid = session('user_auth.uid');
        if ($this->request->isAjax()) {
			
            $data = [
                'key' => $this->request->get('key', '', 'trim'),
                'limit' => $this->request->get('limit', 10, 'intval'),
            ];

            $order_name = empty($this->request->get('field')) ?'sort':$this->request->get('field');
            $order_type = empty($this->request->get('order')) ?'asc':$this->request->get('order');
            $map['status'] = 1;

            $cid = $this->request->get('cid');
            if($cid){
                $map['cate_id'] = $cid;
            }
			$cate_ids = Db::name('cate')->where('delete_time','>',0)->column('id');
            if(!empty($cate_ids)){
				$list = ArticleModel::where($map)->where('cate_id','not in',$cate_ids)->withSearch(['title'], ['title' => $data['key']])->order($order_name.' '.$order_type.',a_id desc')->paginate($data['limit'], false, ['query' => $data]);
            }else{
				$list = ArticleModel::where($map)->withSearch(['title'], ['title' => $data['key']])->order($order_name.' '.$order_type.',a_id desc')->paginate($data['limit'], false, ['query' => $data]);
			}

            
            $user_date = [];
            foreach ($list as $key => $val) {
                $user_date[$key] = $val;
                $user_date[$key]['catetitle'] = $val->catetitle;
            }
            return show($user_date, 0, '', ['count' => $list->total()]);
        }

        //$cate_list = CateService::cate_tree_three();
		
		
		$tree_attr = CateModel::field('id,parent_id,title,type')->where('status',1)->order('sort asc,id asc')->select();
		
		$data = ArrayOperate::arrayToTreexc($tree_attr->toArray());
		$cate_list = ArrayOperate::treeToArray($data);
		
		
        return $this->fetch('',['cate_list'=>$cate_list]);
        
    }
	
	
	

    public function edit(){
       if ($this->request->isPost()) {
            $data = $this->request->post();
			
			$validate = validate('Article');
			if (!$validate->check($data)) {
				//令牌数据无效时重置令牌
				$validate->getError() != '令牌数据无效' ? $token = Request::token() : $token = '';
				$msg = Result::error($validate->getError(), null, ['token' => $token]);
				return $msg;
			}
           // if ($data['is_hot_b'] == 1){
           //     ArticleModel::update(['is_hot_b'=>0],['is_hot_b' =>1]);
           // }
		   $type = Db::name('cate')->where('id',$data['cate_id'])->value('type');
		   if(in_array($type,[6,8,3,4,5])){
			   $this->error('此栏目下不能添加文章');
		   }
           if ($data['a_id']) {
                //编辑
                $res = ArticleModel::update($data, ['a_id' => $data['a_id']]);
                if ($res) {
                    $msg = Result::success('编辑成功', url('/admin/article-list'));
                } else {
                    $msg = Result::error('编辑失败');
                }
            } else {
                //添加
                $ArticleModel = new ArticleModel;
                $res = $ArticleModel->allowField(true)->save($data);
                if ($res) {
                    $msg = Result::success('添加成功', url('/admin/article-list'));
                } else {
                    $msg = Result::error('添加失败');
                }
            }


           return $msg;

        } else {
            $a_id = $this->request->get('a_id', 0, 'intval');
            if ($a_id) {
                $list = ArticleModel::where('a_id', '=', $a_id)->find();
            }else{
                $list['files'] = '';
                $cid = $this->request->get('cid',0);
                $list['cate_id'] = $cid;
            }
			
				$files = explode(',',$list['files']);
			   $files = array_filter($files);
			   $this->assign('files', $files);
			   $files_js = json_encode($files);
			
			$this->assign('files_js', $files_js);
           

           //$list['files'] = implode(',',$files);

            $cate_list = CateService::cate_tree_three();
            $this->assign('list', $list);
			
			$cate_attr = CateModel::field('id,parent_id,title')->where('status',1)->order('id asc,sort desc')->select();
        	$cate_option_str = ArrayOperate::arrayToSelect($cate_attr->toArray(), $list['cate_id']);
			$this->assign('cate_option_str', $cate_option_str);
			$img_size = '';
			if(!empty($list['cate_id'])){
				$type = Db::name('cate')->where('id',$list['cate_id'])->value('type');
				$img_size = Db::name('cate')->where('id',$list['cate_id'])->value('img_size');
 
				//$tpl = 'edit_'.$type;
				if($type == 1 || $type == 10){
					$img_size = !empty($img_size)?$img_size:'(500*200)';
					$tpl = 'edit';
				}elseif($type == 2){
					$tpl = 'edit_product';
				}elseif($type == 9){
					$tpl = 'edit_url';
				}else{
					$tpl = 'edit_default';
				}
			}elseif($list['cate_id'] == 2){
				$tpl = 'edit_default';
			}
            return $this->fetch($tpl,['cate_list'=>$cate_list,'img_size'=>$img_size]);
        } 
        
    }

    public function see(){
        $a_id = $this->request->get('a_id', 0, 'intval');
        if ($a_id) {
            $list = ArticleModel::where('a_id', '=', $a_id)->find();
        }else{
            $list['files'] = '';
            $cid = $this->request->get('cid',0);
            $list['cate_id'] = $cid;
        }

        $files = explode(',',$list['files']);
        $files = array_filter($files);
        //dump($this->request->domain());die;
        foreach ($files as $k=>$v){
            //$files[$k] =  urldecode(urlencode($this->request->domain().$v));
            $files[$k] = str_replace('#','%23',$v);
        }
        $this->assign('files', $files);

        //$list['files'] = implode(',',$files);
        $files_js = json_encode($files);
        $this->assign('files_js', $files_js);

        $cate_list = CateService::cate_tree_three();
        $this->assign('list', $list);
        return $this->fetch('',['cate_list'=>$cate_list]);
    }

    public function del(){
        $a_id = $this->request->param('a_id', 0, 'intval');
        if ($a_id) {
                $res = ArticleModel::where('a_id='.$a_id)->delete();
                if ($res) {
                    $msg = Result::success('删除成功');
                } else {
                    $msg = Result::error('删除失败');
                }
        
                return $msg;
            
        } else {
            $this->error('参数错误');
        }
        
    }
    
    
    //清空
	public function delall()
    {
        $res = Db::name('')->delete(true);
        if ($res) {
            $msg = Result::success('操作成功');
        } else {
            $msg = Result::error('操作失败');
        }
        return $msg;
    }

    public function daochuall()
    {

        $data = [
            'key' => $this->request->get('key', '', 'trim'),
            'limit' => $this->request->get('limit', 10, 'intval'),
        ];
        $order_name = empty($this->request->get('field')) ?'sort':$this->request->get('field');
        $order_type = empty($this->request->get('order')) ?'asc':$this->request->get('order');
        $map['status'] = 1;
        $cid = $this->request->get('cid');
        if($cid){
            $child =  getAllChildId($cid);
            $child = $child?$child:[];
            array_push($child,$cid);
            $map['cate_id'] = $child;
        }

        $list = ArticleModel::where($map)->withSearch(['title'], ['title' => $data['key']])->order($order_name.' '.$order_type.',a_id desc')->select();

        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        //设置行高度
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        // set table header content
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','序号')
            ->setCellValue('B1', '保存日期')
            ->setCellValue('C1', get_show_name('cate_id'))//'文件分类'
            ->setCellValue('D1', get_show_name('sn'))//'文件编号'
            ->setCellValue('E1', get_show_name('title'))//'文件名称'
            ->setCellValue('F1', get_show_name('subject'))//'文件主题'
            ->setCellValue('G1', get_show_name('storage_location'))//'存放位置'
            ->setCellValue('H1', get_show_name('desc'))//'文件内容'
            ->setCellValue('I1', get_show_name('remarks'))//'文件备注'
            ->setCellValue('J1', get_show_name('zdy1'))//'自定义1'
            ->setCellValue('K1', get_show_name('zdy2'))//'自定义'
            ->setCellValue('L1', get_show_name('zdy3'))//'自定义'
            ->setCellValue('M1', get_show_name('zdy4'))//'自定义'
            ->setCellValue('H1', get_show_name('zdy5'))//'自定义'
            ->setCellValue('O1', get_show_name('zdy6'))//'自定义'
            ->setCellValue('P1', get_show_name('zdy7'))//'自定义'
            ->setCellValue('Q1', get_show_name('zdy8'));//'自定义'
        if ($list) {
            for ($i = 0; $i <= count($list) - 1; $i++) {
                //dump($list[$i]['create_time']);die;
                $objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 2), $list[$i]['a_id']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 2), date('Y/m/d',strtotime($list[$i]['create_time'])));
                $objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 2), $list[$i]['catetitle']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($i + 2), $list[$i]['sn']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($i + 2), $list[$i]['title']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($i + 2), $list[$i]['subject']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('G' . ($i + 2), $list[$i]['storage_location']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('H' . ($i + 2), $list[$i]['desc']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('I' . ($i + 2), $list[$i]['remarks']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('J' . ($i + 2), $list[$i]['zdy1']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('K' . ($i + 2), $list[$i]['zdy2']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('L' . ($i + 2), $list[$i]['zdy3']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('M' . ($i + 2), $list[$i]['zdy4']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('N' . ($i + 2), $list[$i]['zdy5']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('O' . ($i + 2), $list[$i]['zdy6']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('P' . ($i + 2), $list[$i]['zdy7']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('Q' . ($i + 2), $list[$i]['zdy8']);
            }
        }
        $objPHPExcel->getActiveSheet()->setTitle('文件列表');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="文件列表_' . date('Y-m-d H:i:s', time()) . '.xlsx"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');  //excel5为xls格式，excel2007为xlsx格式
        ob_end_clean();
        $objWriter->save('php://output');

    }


    public function daoru(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['fileurl'])){
                $this->error('请上传文件');
            }
            $data = import_excel($data['fileurl']);
            if(empty($data)){
                $this->error('文件没有内容');
            }
            if(count($data)<2){
                $this->error('文件没有内容');
            }
            unset($data[0]);

            $array = [];
            //dump($data);die;
            foreach($data as $k=>$v){
                $cate_id = Db::name('cate')->where('title',$v[0])->value('id');
                if(empty($cate_id)){
                    $cate_id = Db::name('cate')->insertGetId(['title'=>$v[0],'create_time'=>time()]);
                }
                $array[$k] = ['cate_id'=>$cate_id,'sn'=>$v[1],'title'=>$v[2],'subject'=>$v[3],'storage_location'=>$v[4],'desc'=>$v[5],'remarks'=>$v[6],'create_time'=>time()];
            }
            Db::startTrans();
            $flag = Db::name('article')->data($array)->limit(100)->insertAll();
            if($flag){
                Db::commit();
                $this->success('导入成功', url('/admin/article-list'));
            }else{
                Db::rollback();
                $this->error('导入失败');
            }

        } else {
            return $this->fetch();
        }
    }

    public function yulan(){

        $data = [
            'key' => $this->request->get('key', '', 'trim'),
            'limit' => $this->request->get('limit', 10, 'intval'),
        ];
        $order_name = empty($this->request->get('field')) ?'sort':$this->request->get('field');
        $order_type = empty($this->request->get('order')) ?'asc':$this->request->get('order');
        $map['status'] = 1;
        $cid = $this->request->get('cid');
        if($cid){
            $child =  getAllChildId($cid);
            $child = $child?$child:[];
            array_push($child,$cid);
            $map['cate_id'] = $child;
        }

        $list = ArticleModel::where($map)->withSearch(['title'], ['title' => $data['key']])->order($order_name.' '.$order_type.',a_id desc')->select();
        return $this->fetch('',['list'=>$list]);

    }

    public function fieldlist(){

        $list = Db::name('article_field')->select();
        return $this->fetch('',['list'=>$list]);
    }


    public function fieldshow(){
        $id = input('post.id');
        if(!$id){
            $this->error('非法操作');
        }
        $is_show = input('post.is_show');
        $res = Db::name('article_field')->where('id='.$id)->update(['is_show'=>$is_show]);
        if ($res) {
            $msg = Result::success('操作成功');
        } else {
            $msg = Result::error('操作失败');
        }
        return $msg;
    }

    public function change_show_name(){
        $id = input('post.id');
        $show_name = input('post.show_name','trim');
        if(!$id || empty($show_name)){
            $this->error('非法操作');
        }
        $res = Db::name('article_field')->where('id='.$id)->update(['show_name'=>$show_name]);
        if ($res !== false) {
            $msg = Result::success('操作成功');
        } else {
            $msg = Result::error('操作失败');
        }
        return $msg;
    }

}




?>